<template>
  <div class="app-container">
    <div class="syl-group">
      <el-form ref="queryForm" :model="queryParams" :inline="true" @submit.native.prevent>
        <el-form-item label="商品名称:" prop="dishName">
          <el-input
            v-model.trim="queryParams.dishName"
            placeholder="请输入"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" size="mini" class="ordinary" style="margin-right: 20px" @click="resetQuery">
            重置
          </el-button>
          <el-button type="primary" size="mini" @click="handleAdd">新增配菜</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <span class="syl-span">菜品分类:</span>
          <el-radio-group v-model="queryParams.dishType1" @change="getDishType">
            <el-radio :label="3">全部菜品</el-radio>
            <el-radio :label="1">只看主菜</el-radio>
            <el-radio :label="2">只看配菜</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <span class="syl-span">菜品状态:</span>
          <el-radio-group v-model="queryParams.status1" @change="getStatusValue">
            <el-radio :label="3">全部状态</el-radio>
            <el-radio :label="1">只看上架</el-radio>
            <el-radio :label="2">只看下架</el-radio>
          </el-radio-group>
        </el-col>
      </el-row>
      <div v-if="equWristbandList.length>0" class="syl-box">
        <el-card v-for="item in equWristbandList" :key="item.id" class="syl-card" shadow="never">
          <div class="syl-card-hennd">
            <div class="hamger">
              <img :src="serverMap.baseImg + '/'+getCuisine(item.dishImage,0)" alt="套餐图片" :onerror="defaultImg">
            </div>
            <div class="syl-frame">
              <div class="middle">
                <div class="middle-left">
                  <span style="margin-right: 15px" v-html="getNullNames(item.dishName)" />
                  <el-button v-if="item.dishType===1" type="warning" size="mini">主菜</el-button>
                  <el-button v-if="item.dishType===2" type="warning" size="mini">配菜</el-button>
                </div>
              </div>
              <div class="menu" v-html="'烹饪方式:'+getNullNames(item.cookingMethodName)" />
              <div class="quantity" v-html="'菜品分类:'+getNullNames(item.dishCategoryName)" />
            </div>
          </div>
          <div class="bottom">
            <div class="bottom-left">
              <el-button icon="el-icon-refresh" size="mini" class="ordinary" @click="handleUpdate(item.id)">查看
              </el-button>
            </div>
            <el-divider direction="vertical" />
            <div v-if="item.status===2" class="bottom-right">
              <el-button type="primary" size="mini" @click="getStatus(item)">商品上架</el-button>
            </div>
            <div v-if="item.status===1" class="bottom-right">
              <el-button type="primary" size="mini" @click="getStatus(item)">商品下架</el-button>
            </div>
          </div>
        </el-card>
      </div>
      <div v-else>
        <h2>暂无数据</h2>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改门店对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1080px"
      append-to-body
      :lock-scroll="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-dialog
        width="560px"
        title="添加原料"
        :visible.sync="innerVisible"
        append-to-body
      >
        <el-form ref="form1" :model="form1" :rules="rules1" label-width="120px">
          <el-form-item label="添加原料单位" prop="materialId">
            <el-select
              v-model="form1.materialId"
              placeholder="请选择菜品种类"
              style="width: 100%"
              filterable
              @change="getTest"
            >
              <el-option
                v-for="item in rawMaterial"
                :key="item.id"
                :label="item.materialName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="原料数量" prop="amount">
            <el-input v-model.trim="form1.amount" placeholder="请输入原料数量" style="width:50%" :maxlength="5" />
            <el-select v-model="form1.materialId" :disabled="true" placeholder="请选择单位" style="width: 40%">
              <el-option
                v-for="item in rawMaterial"
                :key="item.id"
                :label="item.unitName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" style="float: left" @click="submitFormLeft">保 存 并 继 续</el-button>
          <el-button @click="cancel1">关 闭</el-button>
          <el-button type="primary" @click="submitForm2">确 定</el-button>
        </div>
      </el-dialog>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="30">
          <el-col :span="11">
            <el-form-item label="菜品名称" prop="dishName">
              <el-input v-model.trim="form.dishName" placeholder="请输入菜品名称" :maxlength="10" />
            </el-form-item>
            <el-form-item label="制作方式" prop="cookingMethodId">
              <el-select v-model="form.cookingMethodId" style="width: 100%" filterable placeholder="请选择">
                <el-option
                  v-for="item in makeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="菜品图片" prop="imga">
              <el-upload
                ref="upload"
                :action="upload.url"
                :headers="upload.headers"
                :disabled="upload.isUploading"
                list-type="picture-card"
                :file-list="fileList"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :before-upload="beforeAvatarUpload"
                :limit="limitCount"
                :on-success="handleAvatarSuccess"
                :on-exceed="handleAvatarData"
                :class="[hideUpload===3?'hide':'']"
              >
                <i class="el-icon-plus" />
              </el-upload>
            </el-form-item>
            <el-form-item label="菜品分类" prop="dishType">
              <el-switch
                v-model="form.dishType"
                active-text="主菜"
                inactive-text="配菜"
                :active-value="1"
                :inactive-value="2"
              />
            </el-form-item>
            <el-form-item label="菜品简介" prop="introduction">
              <el-input
                v-model="form.introduction"
                type="textarea"
                :autosize="{ minRows: 5, maxRows: 10}"
                placeholder="请输入菜品描述"
                maxlength="500"
                show-word-limit
                resize="none"
              />
            </el-form-item>
          </el-col>
          <el-col :span="13">
            <el-form-item label="菜品种类" prop="dishCategoryId">
              <el-select v-model="form.dishCategoryId" style="width: 280px" filterable placeholder="请选择菜品种类">
                <el-option
                  v-for="item in varietyDishes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="菜品原料" prop="cookMaterialSaveBoList">
              <el-button type="primary" @click="material">添 加 原 料</el-button>
            </el-form-item>
            <div class="syl-tal">
              <el-row :gutter="10">
                <el-col v-for="item in form.cookMaterialSaveBoList" :key="item.id" :span="11" class="syl-raw">
                  <span v-html="item.materialName+item.amount + item.unitName" />
                  <el-button type="danger" icon="el-icon-delete" size="small" circle style="float: right" @click="getDelete(item.id)" />
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-divider direction="vertical" />
        <el-button v-preventReClick type="primary" :loading="lodaing" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!--照片弹窗-->
    <el-dialog
      :title="title1"
      :visible.sync="dialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div style="width: 100%;text-align: center">
        <img style="width: 240px;height: 170px" :src="dialogImageUrl" alt="">
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import { addDishList, getById, getDishList, updateStatus } from '@/api/commodity/variety'
import serverMap from '../../../../config/serverMap'
import { listDishMaterial } from '@/api/commodity/material'
import { getCooking, getDishes } from '@/api/commodity/classification'
import userPhoto from '@/assets/image/flase.png'
import * as imageConversion from 'image-conversion'

export default {
  name: 'Index',
  data() {
    return {
      defaultImg: 'this.src="' + userPhoto + '"',
      fileList: [],
      limitCount: 3,
      hideUpload: false,
      dialogImageUrl: null,
      dialogVisible: false,
      serverMap: serverMap,
      // 遮罩层
      loading: false,
      lodaing: false,
      // 制作
      makeList: [],
      // 菜品种类
      varietyDishes: [],
      // 原料
      rawMaterial: [],
      // 主菜
      selectedOptions: [],
      // 配菜 1，2
      sideDishes1: [],
      sideDishes2: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 套餐表格数据
      equWristbandList: [],
      // 状态
      options: [],
      // 弹出层标题
      title: '',
      title1: '',
      // 是否显示弹出层
      open: false,
      //  嵌套弹出层
      innerVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dishName: undefined,
        // 菜品状态
        dishType: null,
        status: null,
        dishType1: 3,
        status1: 3
      },
      imageUrl: '',
      // 表单参数
      form: {
        cookMaterialSaveBoList: [],
        cookingMethodId: undefined,
        dishCategoryId: undefined,
        suplyCompany: undefined,
        dishType: 2,
        introduction: undefined,
        dishImage: [],
        dishName: undefined,
        status: 1,
        id: undefined
      },
      // 表单校验
      rules: {
        introduction: [
          { required: true, message: '菜品详情不能为空', trigger: 'blur' }
        ],
        dishName: [
          { required: true, message: '菜品名称不能为空', trigger: 'blur' },
          {
            pattern: /[\u4e00-\u9fa5]/,
            message: '菜品名称只能为中文',
            trigger: 'blur'
          }
        ],
        cookingMethodId: [
          { required: true, message: '制作方式不能为空', trigger: 'blur' }
        ],
        dishCategoryId: [
          { required: true, message: '菜品种类不能为空', trigger: 'blur' }
        ],
        cookMaterialSaveBoList: [
          { required: true, message: '菜品原料不能为空', trigger: 'blur' }
        ]
      },
      form1: {
        materialName: undefined,
        unitId: undefined,
        amount: undefined,
        id: undefined,
        unitName: undefined
      },
      rules1: {
        materialId: [
          { required: true, message: '原料名称不能为空', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '原料数量不能为空', trigger: 'blur' }
        ]
      },
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: serverMap.base + '/api/sys/files/upload'
      }
    }
  },
  created() {
    this.getList()
    this.getDateList()
    this.getCookingList()
    this.getDishesList()
  },
  methods: {
    /** 查询菜单列表 */
    getList() {
      const { dishType1, status1 } = this.queryParams
      if (dishType1 !== 3) {
        this.queryParams.dishType = dishType1
      } else {
        this.queryParams.dishType = null
      }
      if (status1 !== 3) {
        this.queryParams.status = status1
      } else {
        this.queryParams.status = null
      }
      getDishList(this.queryParams).then(res => {
        const { total, records } = res.data
        this.total = total
        this.equWristbandList = records
      })
    },
    /** 原料单位数据列表 **/
    getDateList() {
      listDishMaterial().then(res => {
        const { data } = res
        this.rawMaterial = data
      })
    },
    /** 获取制作方式 **/
    getCookingList() {
      getCooking(this.queryParams).then(res => {
        const { data } = res
        this.makeList = data
      })
    },
    /** 获取菜品分类 **/
    getDishesList() {
      getDishes(this.queryParams).then(res => {
        const { data } = res
        this.varietyDishes = data
      })
    },
    /** 菜品分类 **/
    getDishType(value) {
      this.queryParams.dishType1 = value
      this.getList()
    },
    /** 菜品状态 **/
    getStatusValue(value) {
      this.queryParams.status1 = value
      this.getList()
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.$refs.upload.clearFiles()
      this.reset()
    },
    //  嵌套取消
    cancel1() {
      this.innerVisible = false
      this.reset1()
    },
    /** 添加菜单材料 **/
    material() {
      this.reset1()
      this.innerVisible = true
    },
    // 表单重置
    reset() {
      this.lodaing = false
      this.form = {
        cookMaterialSaveBoList: [],
        cookingMethodId: undefined,
        dishCategoryId: undefined,
        suplyCompany: undefined,
        dishType: 2,
        introduction: undefined,
        dishImage: [],
        dishName: undefined,
        status: 1,
        id: undefined
      }
      this.resetForm('form')
    },
    reset1() {
      this.form1 = {
        materialName: undefined,
        unitId: undefined,
        amount: undefined,
        id: undefined,
        unitName: undefined
      }
      this.resetForm('form1')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.status1 = 3
      this.queryParams.dishType1 = 3
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加菜单'
      this.$nextTick(() => {
        this.$refs.upload.clearFiles() // 清空文件
      })

      this.fileList = []
    },
    /** 修改上架和下架状态 **/
    getStatus(row) {
      const data = {
        id: row.id,
        status: row.status === 1 ? 2 : 1
      }
      const text = row.status === 1 ? '下架' : '上架'
      const name = row.status === 1 ? '下架此菜品后，将无法在添加到新的套餐内.' : '上架此菜品后，允许添加到新的套餐内'
      this.$confirm('是否确定' + text + row.dishName + '吗?' + '<br/>' + '<span style="color: #999999">' + name + '</span>', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(function() {
        return updateStatus(data)
      }).then(() => {
        this.msgSuccess(text + '成功')
        this.getList()
      }).catch(function() {
        return row.status
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.fileList = []
      const arr = [null, undefined, '']
      getById(row).then(res => {
        const { dishImage } = res.data
        this.form = res.data
        if (arr.includes(dishImage)) {
          this.form.dishImage = []
        } else {
          const dishImage1 = res.data.dishImage.split(',')
          this.fileList = dishImage1.map(item => {
            return {
              url: serverMap.baseImg + '/' + item
            }
          })
          this.hideUpload = this.fileList.length
          this.form.dishImage = dishImage1
        }
        this.title = '编辑套餐'
        this.open = true
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      const { dishImage } = this.form
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.lodaing = true
          if (JSON.stringify(dishImage) !== '[]') {
            this.form.dishImage = dishImage.join(',')
          } else if (typeof dishImage === 'string') {
            this.msgInfo('请至少上传一张图片')
          } else {
            this.form.dishImage = dishImage
          }
          addDishList(this.form).then(res => {
            if (!res.code) {
              this.open = false
              this.lodaing = false
              this.msgSuccess('操作成功')
              this.getList()
            }
          })
        }
      })
      setTimeout(() => {
        this.lodaing = false
      }, 3000)
    },
    /** 嵌套菜品原料提交按钮 **/
    submitForm2: function() {
      this.$refs['form1'].validate((valid) => {
        if (valid) {
          const { cookMaterialSaveBoList } = this.form
          const { materialId } = this.form1
          const checkArrayRepeat = cookMaterialSaveBoList.map((item) => item.materialId)
          const index = checkArrayRepeat.indexOf(materialId)
          if (index !== -1) {
            return this.msgInfo('不可重复添加原料')
          }
          this.innerVisible = false
          this.form.cookMaterialSaveBoList.push(JSON.parse(JSON.stringify(this.form1)))
        }
      })
    },
    submitFormLeft: function() {
      this.$refs['form1'].validate((valid) => {
        if (valid) {
          const { cookMaterialSaveBoList } = this.form
          const { materialId } = this.form1
          const checkArrayRepeat = cookMaterialSaveBoList.map((item) => item.materialId)
          const index = checkArrayRepeat.indexOf(materialId)
          if (index !== -1) {
            return this.msgInfo('不可重复添加原料')
          }
          this.form.cookMaterialSaveBoList.push(JSON.parse(JSON.stringify(this.form1)))
          this.reset1()
        }
      })
    },
    /** 获取原料单位的值**/
    getTest(row) {
      let name = {}
      name = this.rawMaterial.find(item => item.id === row)
      this.form1.materialName = name.materialName
      this.form1.unitName = name.unitName
    },
    /** 删除原料 **/
    getDelete(id) {
      this.form.cookMaterialSaveBoList = this.form.cookMaterialSaveBoList.filter(item => item.id !== id)
    },
    /** 点击文件列表中已上传的文件时的钩子 **/
    handlePictureCardPreview(file) {
      this.title1 = '查看图片'
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 超出事件
    handleAvatarData() {
      this.msgInfo('图片上传次数最多为3张!')
    },
    // 上传成功
    handleAvatarSuccess(res, file, fileList) {
      if (res.code === 0) {
        const { data } = res
        this.form.dishImage.push(data.url)
        this.hideUpload = fileList.length >= this.limitCount
      }
    },
    /** 图片删除 */
    handleRemove(file, fileList) {
      this.form.dishImage = fileList.map((item) => item.url)
      this.hideUpload = fileList.length >= this.limitCount
    },
    /** 图片上传格式判断 */
    beforeAvatarUpload(file) {
      new Promise((resolve, reject) => {
        const isJPG = file.type.split('/')[1]
        const value = ['jpeg', 'png', 'jpg', 'bmp', 'gif', 'JPEG', 'PNG', 'JPG', 'BMP']
        const name = value.includes(isJPG)
        if (!name) {
          this.msgError('上传图片格式为' + 'jpeg', 'png', 'jpg', 'bmp', 'gif', 'JPEG', 'PNG', 'JPG', 'BMP')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        const _URL = window.URL || window.webkitURL
        // 这里需要计算出图片的长宽
        const img = new Image()
        img.onload = function() {
          file.width = img.width // 获取到width放在了file属性上
          file.height = img.height // 获取到height放在了file属性上
          const valid = img.width > 2000 // 图片宽度大于2000
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (valid || isLt2M) {
            imageConversion.compressAccurately(file, {
              size: 400,
              width: 2000
            }).then(res => { // console.log(33, res)
              resolve(res)
            })
          } else {
            resolve(file)
          }
        } // 需要把图片赋值
        img.src = _URL.createObjectURL(file)
        if (!isLt2M) {
          this.msgError('上传头像图片大小不能超过 2MB,请重新上传!')
        }
        return name && isLt2M
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.syl-span {
  font-weight: 700;
  font-size: 14px;
  color: #606266;
  padding: 0 12px 0 0;
}

.syl-tal {
  width: 100%;
  height: auto;
  .syl-raw {
    height: 40px;
    font-size: 14px;
    line-height: 40px;
    margin: 5px 5px;
    background-color: #cccccc;
    border-radius: 5px;
    text-align: left;
  }
}

.mb8 {
  margin-bottom: 20px;
}

/deep/ .el-card__body {
  padding: 0;
}

.syl-frame {
  width: 100%;
  padding: 0 15px;
}

/** 卡片样式 **/
.syl-card {
  width: 286px;
  margin: 10px 10px;
  display: inline-block;

  .syl-card-hennd {
    width: 100%;
    height: auto;

    .hamger {
      width: 100%;
      height: 160px;
      text-align: center;
      border-radius: 5px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .middle {
      width: 100%;
      font-size: 16px;
      line-height: 50px;
      display: flex;

      .middle-left {
        width: 100%;
        height: 50px;
        text-align: left;
        font-size: 16px;
        font-weight: 600;
        color: #333333;
      }

      .middle-right {
        width: 50%;
        height: 50px;
        text-align: right;
        font-size: 14px;
        font-weight: 400;
        color: #999999;
      }
    }

    .menu {
      width: 100%;
      height: 35px;
      line-height: 35px;
      font-size: 14px;
      font-weight: 400;
      color: #333333;
    }

    .quantity {
      height: 35px;
      line-height: 35px;
      display: inline-block;
      font-size: 14px;
      font-weight: 400;
      color: #666666;
    }

    .darter {
      height: 35px;
      line-height: 35px;
      float: right;

      .darter-left {
        color: #EC1717;
        font-size: 22px;
        font-weight: 400;
      }

      .darter-right {
        font-size: 12px;
        color: #666666;
        font-weight: 400;
      }
    }
  }

  .bottom {
    width: 100%;
    height: 50px;
    border-top: 2px solid #F2F2F2;
    padding: 8px 0;
    text-align: center;
    font-size: 16px;
    display: flex;
    color: #cccccc;
    cursor: pointer;

    .bottom-left {
      width: 50%;
    }

    .bottom-right {
      width: 50%;
    }
  }
}

/deep/ .el-divider--vertical {
  margin: 6px 15px;
}
</style>
